<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <div class="login-header">
          <h2>用户登录</h2>
        </div>
      </template>

      <el-form
          ref="loginForm"
          :model="form"
          :rules="rules"
          label-width="80px"
          @keyup.enter="handleLogin"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
              v-model="form.username"
              placeholder="请输入用户名"
              clearable
          >
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
              v-model="form.password"
              type="password"
              placeholder="请输入密码"
              show-password
              clearable
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-checkbox v-model="rememberMe">记住我</el-checkbox>
          <el-link type="primary" underline="always" class="forgot-link">忘记密码?</el-link>
        </el-form-item>

        <el-form-item>
          <el-button
              type="primary"
              class="login-btn"
              @click="handleLogin"
              :loading="loading"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>

</template>

<script>
import { ref, reactive ,computed} from 'vue'
import { User, Lock} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import router from "@/router";
import axios from "axios";
import {useStore} from "vuex";
import generateRouter from "../hooks/common/generateRouter";

export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name:'Login',
  components:{User,Lock},
  emits:['login'],
  setup(props,context){
    // 表单数据
    const form = reactive({
      username: '',
      password: ''
    })

    // 记住我
    const rememberMe = ref(false)


    // 表单验证规则
    const rules = reactive({
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 4, max: 16, message: '长度在 4 到 16 个字符', trigger: 'blur' }
      ]
    })

    // 引用表单实例
    const loginForm = ref(null)
    const loading = ref(false)
    const store = useStore()
    // 登录处理
    const handleLogin = async () => {
      // 表单验证
      loginForm.value.validate().then(()=>{
        login(form)
        loading.value = false
        loginForm.value.resetFields()
      }).catch(err=>{
        console.error('验证不通过，请检查用户名或密码输入是否正确:',err)
        ElMessage.error('验证不通过，请检查用户名或密码输入是否正确')
      })


    }

    //登录功能
    function login(form){
      loading.value = true
      let staffInfo = computed(()=>store.state.staffInfo)
      if (staffInfo) {
        router.replace('/')
      }
      axios.post('http://localhost:8888/login',{username:form.username,password:form.password}).then(resp=>{
        console.log('resp.data.code===>:',resp.data.code)
        if (resp.data.code=='00000'){
          ElMessage.success(resp.data.message)
          localStorage.setItem('staffInfo',JSON.stringify(resp.data.data))
          //加载侧边栏导航节点
          store.dispatch('addMenuItemList')
          //添加用户信息
          store.dispatch('addStaffInfo',resp.data.data)
          //用户登录后添加路由
          generateRouter().then((routes)=>{
            routes.forEach(route=>{
              if (!router.hasRoute(route.routeName)){
                router.addRoute(route)
              }
            })
            router.replace({name:'home'})
          }).catch(err=>{
            ElMessage.error(err)
            console.log(err)
          })
        }else {
          ElMessage.error(resp.data.message)
          console.log(resp.data.message)
        }
      }).catch(error=>{
        ElMessage.error(error.message)
        console.log(error.message)
      })
    }

    return {handleLogin,rules,rememberMe,form,loginForm,loading}
  }
}


</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-card {
  width: 450px;
  border-radius: 10px;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1);
}

.login-header {
  text-align: center;
  padding: 10px 0;
  color: #409EFF;
}

.forgot-link {
  float: right;
}

.login-btn {
  width: 100%;
  height: 45px;
  font-size: 16px;
  letter-spacing: 5px;
}

.login-footer {
  margin-top: 20px;
}

.social-login {
  display: flex;
  justify-content: center;
  gap: 25px;
  margin-top: 15px;
}

.icon {
  font-size: 28px;
  color: #606266;
  cursor: pointer;
  transition: all 0.3s;
}

.icon:hover {
  color: #409EFF;
  transform: scale(1.2);
}

.el-divider {
  margin: 20px 0;
}
</style>